package com.jlb.jolokia.example.restrictor;

import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

/**
 * Wrapper class used to encapsulate an {@link ObjectName} (MBean definition)
 * with a corresponding operation.
 * 
 * @author Justin Braathen
 */
class JolokiaOperation {

	/**
	 * The MBean representation
	 */
	private ObjectName objectName;

	/**
	 * A {@link String} array of operations allowed for this MBean
	 * <p>
	 * Example:
	 * <p>
	 * <li>stop()
	 * <li>start()
	 * <li>suspend()
	 */
	private String[] allowedOperations;

	/**
	 * Constructs a new instance of a {@link JolokiaOperation} wrapper object.
	 * <p>
	 * 
	 * @param inObjectName
	 *            : The canonical {@link String} representation of an MBean
	 * @param inAllowedOperations
	 *            : A {@link String} array of operations allowed for this MBean
	 * @throws MalformedObjectNameException
	 */
	public JolokiaOperation(String inObjectName, String... inAllowedOperations)
			throws MalformedObjectNameException {
		this.objectName = new ObjectName(inObjectName);
		this.allowedOperations = inAllowedOperations;
	}

	/**
	 * Utility method to determine if an MBean is allowed. Confirms that 1)
	 * MBean is allowed and 2) Operation on specific MBean is allowed.
	 * 
	 * @param otherObjectName
	 * @param otherOperation
	 * @return Returns true if the MBean and operation is allowed.
	 */
	boolean isAllowed(ObjectName otherObjectName, String otherOperation) {
		if (!this.objectName.equals(otherObjectName)) {
			return false;
		}

		for (String allowedOperation : allowedOperations) {
			if (allowedOperation.equals(otherOperation)) {
				return true;
			}
		}

		return false;
	}

}
